/*
 * Created by Jaren at 2022/1/28 9:31
 */
import 'dart:io';
import 'dart:typed_data';

import 'package:inmotion_protocol/lorin/file/lorin_file.dart';

class FileUtils {
  static Uint8ClampedList getFileContentSync(File file, int size) {
    return Uint8ClampedList.fromList(file.readAsBytesSync());
  }

  static String getFileNameNoFormat(String filePath, {String}) {
    if (filePath == '') {
      return "";
    }
    int point = filePath.lastIndexOf('.');
    int separatorIndex = filePath.lastIndexOf(LorinFile.fileSeparator);
    if (point > 0) {
      if (separatorIndex > 0) {
        return filePath.substring(separatorIndex + 1, point);
      } else {
        return filePath.substring(0, point);
      }
    } else {
      if (separatorIndex > 0) {
        return filePath.substring(separatorIndex + 1, filePath.length);
      } else {
        return filePath;
      }
    }
  }

  static void rewriteFile(File file, int fileOffset, Uint8ClampedList bytes, [int length = -1]) {
    if (length == -1) length = bytes.length;
    Uint8ClampedList fileBytes = getFileContentSync(file, file.lengthSync());
    for (var i = 0; i < length; i++) {
      fileBytes[fileOffset + i] = bytes[i];
    }
    file.writeAsBytesSync(fileBytes, flush: true);
  }
}
